package crypto

import (
	"bytes"
	"crypto"
	"crypto/aes"
	"crypto/cipher"
	"crypto/md5"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/hex"
	"encoding/pem"
	"errors"
	"fmt"
	"io"
	"strconv"
)

/// RSA

func ParsePublicKey(pubkey []byte) (*rsa.PublicKey, error) {
	block, _ := pem.Decode(pubkey)
	if block == nil {
		return nil, errors.New("pub key err")
	}
	pub, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return pub.(*rsa.PublicKey), nil
}

func ParsePrivateKey(privkey []byte) (*rsa.PrivateKey, error) {
	block, _ := pem.Decode([]byte(privkey))
	if block == nil {
		return nil, errors.New("priv key err")
	}
	return x509.ParsePKCS1PrivateKey(block.Bytes)
}

func RsaEncrypt(pub *rsa.PublicKey, data []byte) (string, error) {
	b, err := rsa.EncryptPKCS1v15(rand.Reader, pub, data)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(b), nil
}

func RsaDecrypt(priv *rsa.PrivateKey, data string) ([]byte, error) {
	b, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, b)
}

func RsaSign(priv *rsa.PrivateKey, data []byte) (string, error) {
	hashed := sha256.Sum256(data)
	sig, err := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, hashed[:])
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(sig), nil
}

func RsaVerify(pub *rsa.PublicKey, data []byte, sig string) bool {
	sigb, err := hex.DecodeString(sig)
	if err != nil {
		return false
	}
	hashed := sha256.Sum256(data)
	return rsa.VerifyPKCS1v15(pub, crypto.SHA256, hashed[:], sigb) == nil
}

/// AES

/*
 * 采用CBC模式
 * 数据的前32字节(aes.BlockSize*4)为HEX编码的IV,解码至16字节后使用
 * 32字节后的数据为实际密文，使用PKCS5|7填充至16字节整数倍
 */

/*
func AesEncrypt_old(key string, plaindata []byte) (string, error) {
	if len(key) != 32 {
		return "", errors.New("invalid decrypt key")
	}
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return "", errors.New("invalid decrypt key")
	}
	data := PKCS5Padding(plaindata, aes.BlockSize)
	cipherdata := make([]byte, len(data))
	iv := make([]byte, aes.BlockSize)
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}
	cipher.NewCBCEncrypter(block, iv).CryptBlocks(cipherdata, data)

	return hex.EncodeToString(iv) + base64.StdEncoding.EncodeToString(cipherdata), nil
}

func AesDecrypt_old(key, cipherdata string) ([]byte, error) {
	if len(key) != 32 {
		return nil, errors.New("invalid decrypt key")
	}
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return nil, errors.New("invalid decrypt key")
	}

	if len(cipherdata) < aes.BlockSize {
		return nil, errors.New("ciphertext too short")
	}

	iv, err := hex.DecodeString(cipherdata[:32])
	if err != nil {
		return nil, err
	}
	b, err := base64.StdEncoding.DecodeString(cipherdata[32:])

	if len(b)%aes.BlockSize != 0 {
		return nil, errors.New("ciphertext is not a multiple of the block size, " + strconv.Itoa(len(b)))
	}

	plaindata := make([]byte, len(b))
	cipher.NewCBCDecrypter(block, iv).CryptBlocks(plaindata, b)

	return PKCS5UnPadding(plaindata, aes.BlockSize)
}
*/

func AesEncrypt_bytes(key string, plaindata []byte) ([]byte, error) {
	if len(key) != 32 {
		return nil, errors.New("invalid decrypt key")
	}
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return nil, errors.New("invalid decrypt key")
	}
	data := PKCS5Padding(plaindata, aes.BlockSize)
	cipherdata := make([]byte, len(data))
	iv := make([]byte, aes.BlockSize)
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return nil, err
	}
	cipher.NewCBCEncrypter(block, iv).CryptBlocks(cipherdata, data)

	return append(iv, cipherdata...), nil
}

func AesEncrypt(key string, plaindata []byte) (string, error) {
	b, err := AesEncrypt_bytes(key, plaindata)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(b), nil
}

func AesDecrypt_bytes(key string, cipherdata []byte) ([]byte, error) {
	if len(key) != 32 {
		return nil, errors.New("invalid decrypt key")
	}
	if len(cipherdata) < aes.BlockSize*2 {
		return nil, errors.New("ciphertext too short")
	}

	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return nil, errors.New("invalid decrypt key")
	}

	iv := cipherdata[:aes.BlockSize]
	b := cipherdata[aes.BlockSize:]
	if len(b)%aes.BlockSize != 0 {
		return nil, errors.New("ciphertext is not a multiple of the block size, " + strconv.Itoa(len(b)))
	}

	plaindata := make([]byte, len(b))
	cipher.NewCBCDecrypter(block, iv).CryptBlocks(plaindata, b)

	return PKCS5UnPadding(plaindata, aes.BlockSize)
}

func AesDecrypt(key, cipherdata string) ([]byte, error) {
	b, err := base64.StdEncoding.DecodeString(cipherdata)
	if err != nil {
		return nil, err
	}
	return AesDecrypt_bytes(key, b)
}

func PKCS5Padding(data []byte, blockSize int) []byte {
	padding := blockSize - len(data)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(data, padtext...)
}

func PKCS5UnPadding(data []byte, blockSize int) ([]byte, error) {
	length := len(data)
	if length == 0 || length%blockSize != 0 {
		return nil, errors.New("invalid data length")
	}
	unpadding := int(data[length-1])
	if unpadding == 0 || unpadding > blockSize {
		return nil, errors.New("invalid padding data")
	}
	padtext := data[length-unpadding:]
	for i := 0; i < unpadding; i++ {
		if padtext[i] != byte(unpadding) {
			return nil, errors.New("invalid padding data")
		}
	}
	return data[:(length - unpadding)], nil
}

///

func SHA1(s string) string {
	h := sha1.New()
	h.Write([]byte(s))
	return fmt.Sprintf("%x", h.Sum(nil))
}

func MD5(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return fmt.Sprintf("%x", h.Sum(nil))
}
